<template>
  <div class="search-suggestion">
      <!-- 点击建议进行搜索
            相当于把输入框中的值改变 即可
            无法在此文件进行修改 数据类型是简单数据类型
            需要让父帮忙
            子传父 自定义事件
       -->
    <van-cell 
    v-for="(text,index) in suggestions"
    :key="index"
    icon="search"
    @click="$emit('search', text)" 
    >
    <!-- 高亮效果 -->
    <span slot="title" v-html="highlight(text)"></span>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestions } from '@/api/search'
// 引入防抖包
import { debounce } from "lodash"
export default {
  name: 'SearchSuggestion',
  components: {},
  props: {
      searchText:{
          type:String,
          required:true
      }
  },
  data () {
    return {
        suggestions:[]//联想建议数据
    }
  },
  computed: {},
  watch: {
      searchText:{
          handler:debounce(function(value){
            this.loadSearchSuggestions(value)
          },500),
          
           immediate: true
      }
  },
  created () {},
  mounted () {},
  methods: {
      async loadSearchSuggestions(q){
          try{
              const {data}=await getSearchSuggestions(q)
            //   console.log(data);
              this.suggestions=data.data.options
          }catch(err){
              this.$toast('获取失败')

          }
      },
      highlight(text){//高亮效果
          const highlightStr=`<span class="active">${this.searchText}</span>`
        //   将正则和replace进行结合
        // 正则之中一切当做字符串 得用正则表达式构造函数
        const reg=new RegExp(this.searchText,'gi')
        return  text.replace(reg, highlightStr)
      }
  }
}
</script>

<style scoped lang="less">
    .search-suggestion{
        
        /deep/   span.active{
            color: #3296fa;
        } 
        
        
    }
</style>
